import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';
import type { User } from '@/types';
import * as authApi from '@/api/auth';

interface AuthState {
  user: User | null;
  accessToken: string | null;
  refreshToken: string | null;
  permissions: string[];
  setAuth: (user: User, accessToken: string, refreshToken: string) => void;
  setUser: (user: User) => void;
  setPermissions: (permissions: string[]) => void;
  clearAuth: () => void;
  hasPermission: (permission: string) => boolean;
  hasAnyPermission: (permissions: string[]) => boolean;
  fetchUserInfo: () => Promise<void>;
  fetchPermissions: () => Promise<void>;
}

export const useAuthStore = create<AuthState>()(
  persist(
    (set, get) => ({
      user: null,
      accessToken: null,
      refreshToken: null,
      permissions: [],

      setAuth: (user, accessToken, refreshToken) => {
        set({ user, accessToken, refreshToken });
        localStorage.setItem('access_token', accessToken);
        localStorage.setItem('refresh_token', refreshToken);
      },

      setUser: (user) => {
        set({ user });
      },

      setPermissions: (permissions) => {
        set({ permissions });
      },

      clearAuth: () => {
        set({
          user: null,
          accessToken: null,
          refreshToken: null,
          permissions: [],
        });
        localStorage.removeItem('access_token');
        localStorage.removeItem('refresh_token');
      },

      hasPermission: (permission) => {
        const { permissions, user } = get();
        // 超级管理员拥有所有权限
        if (user?.type === 'super_admin') {
          return true;
        }
        return permissions.includes(permission);
      },

      hasAnyPermission: (requiredPermissions) => {
        const { permissions, user } = get();
        // 超级管理员拥有所有权限
        if (user?.type === 'super_admin') {
          return true;
        }
        return requiredPermissions.some((perm) => permissions.includes(perm));
      },

      fetchUserInfo: async () => {
        try {
          const response = await authApi.getCurrentUser();
          if (response.data.success) {
            set({ user: response.data.data });
          }
        } catch (error) {
          console.error('Failed to fetch user info:', error);
        }
      },

      fetchPermissions: async () => {
        try {
          const response = await authApi.getCurrentUserPermissions();
          if (response.data.success) {
            set({ permissions: response.data.data });
          }
        } catch (error) {
          console.error('Failed to fetch permissions:', error);
        }
      },
    }),
    {
      name: 'auth-storage',
      storage: createJSONStorage(() => localStorage),
      partialize: (state) => ({
        user: state.user,
        accessToken: state.accessToken,
        refreshToken: state.refreshToken,
      }),
    },
  ),
);

